# -*- coding: utf-8 -*-
from datetime import datetime
from models import Comment, Post
from flask_restful import Resource, reqparse, fields, marshal_with, marshal
from app import app, db
import json
from flask_login import login_required

parser = reqparse.RequestParser()
parser.add_argument('email')
parser.add_argument('body')

resource_fields = {
    'email': fields.String,
    'body': fields.String
}


class CommentApi(Resource):
    method_decorators = [login_required]

    @marshal_with(resource_fields)
    def get(self, pid, id):
        comment = Comment.query.get(id)
        return comment

    def put(self):
        pass

    def delete(self, pid, id):
        comment = Comment.query.get(id)
        post = Post.query.get(pid)
        post.comment_count = post.comment_count - 1
        db.session.delete(comment)
        db.session.commit()
        return {'success': True}


class CommentListApi(Resource):
    def get(self, id):
        return json.dumps(marshal(Comment.query.filter(Comment.post_id == id).all(), resource_fields))

    def post(self, id):
        args = parser.parse_args()
        comment = Comment()
        comment.email = args['email']
        comment.body = args['body']
        comment.status = comment.STATUS_DRAFT
        comment.create_time = datetime.now()
        comment.post_id = id
        post = Post.query.get(id)
        post.comment_count = post.comment_count + 1
        db.session.add(comment)
        db.session.add(post)
        db.session.commit()
        return {'success': True, 'id': comment.id}
